/* eslint-disable no-console */
import React, { Component } from "react";
import { WingBlank, InputItem, Toast } from "antd-mobile";
import MainLayout from "../../../component/mainLayout/mainLayout";
import "./TransferXHBInto.scss";
import yhTools from "../../../tools/yh";
import { channelCode } from "../../../config/Config";
import SendMSGCode from "../../../component/sendMSGCode/sendMSGCode";
import { createForm } from "rc-form";

// const alert = Modal.alert;
class TransferXHBInto extends Component {
	constructor(props) {
		super(props);
		this.state = {
			loadStatus: "1", //'0'：数据加载中，'1'：加载完成，'2'：加载失败
			showMsgBox: false, //控制是否显示发送验证码弹窗
			messageSerialNumber: "", //发送短信成功后返回的流水号
			sendSuccessPhone: "", //发送短信成功后返回的手机号
			productBuyInitData: {
				balanceAmt: "",
				electronicCardNo: "",
				minMoney: "",
				maxTradeAmt: "",
				observeLabel: "",
				productLabel: "",
				increasedMoney: "",
				contactInfos: [
					{
						contractCode: "",
						contractDesc: ""
					}
				]
			},
			productId: this.props.match.params.productId,
			isSelect: false,
			inputValue: "",
			tipMessage: "", //输入框提示语
			buyBtnClass: "btn buy-btn btn-disable",
			purchaseAbleClass: "purchase-all purchase-able" //转入按钮样式
		};

		this.timer1 = null;
	}

	componentDidMount() {
		this.prepareData();
	}

	componentWillUnmount() {
		clearTimeout(this.timer1);
	}

	/**
	 * 加载页面数据
	 */
	prepareData() {
		let _that = this;
		let objs2 = {
			url: "/fm/financeBuyInit",
			params: {
				channelCode: channelCode,
				productId: this.props.match.params.productId
			},
			_alertShow: false
		};

		yhTools.request(objs2).then(res => {
			if (res.code === "0") {
				let productBuyInitData = res.data;
				_that.setState(
					{
						productBuyInitData: productBuyInitData,
						loadStatus: "1"
					},
					function () {
						if (parseFloat(productBuyInitData.balanceAmt) >= 100) {
							_that.setState({
								purchaseAbleClass: "purchase-all purchase-able"
							});
						} else {
							_that.setState({
								purchaseAbleClass: "purchase-all purchase-disable"
							});
						}
					}
				);
			} else {
				Toast.info(res.message, 2);
				_that.setState({
					loadStatus: "2"
				});
			}
		});
	}

	//合同点击
	proClick(contractCode) {
		let pageData = {
			inputValue: this.state.inputValue,
			...this.state.productBuyInitData.contactReviewInfos
		};
		this.props.history.push({
			pathname: this.matchAgreement(contractCode),
			state: pageData
		});
	}
	//
	matchAgreement(code) {
		let agreementPath = "";
		switch (code) {
			case "HT11006": // A产品
				agreementPath = "/Exclusiveproductagreement1A";
				break;
			case "HT11007": // B产品
				agreementPath = "/Exclusiveproductagreement1B";
				break;
			default:
				agreementPath = "";
				break;
		}
		return agreementPath;
	}

	//购买
	purchaseClick() {
		if (this.refs.buyProduct.className.split(" ")[2] != "btn-able") {
			return;
		}
		let _that = this;

		if (this.state.productBuyInitData.saleStatus === "2") {
			Toast.info("已售罄");
			return;
		}
		if (this.state.productBuyInitData.saleStatus === "0") {
			Toast.info("已停售");
			return;
		}

		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			_that.sendYzm();
		}, 300);
		// this.getCode();
	}

	//填充全部金额
	allBuyAction() {
		if (parseFloat(this.state.productBuyInitData.balanceAmt) == 0) {
			return;
		}
		this.setState(
			{
				inputValue: this.formatMoney(this.state.productBuyInitData.balanceAmt)
			},
			function () {
				this.checkValue(this.state.inputValue);
			}
		);
	}

	//同意协议
	selectClick() {
		if (this.refs.selectAgree.className.split(" ")[2] == "selected") {
			this.setState(
				{
					isSelect: false
				},
				function () {
					this.checkValue(this.state.inputValue);
				}
			);
		} else {
			this.setState(
				{
					isSelect: true
				},
				function () {
					this.checkValue(this.state.inputValue);
				}
			);
			// alert('', '请确定本人已阅读相关协议且已理解上述内容，并承担相关风险', [
			//     {
			//         text: '取消',
			//         onPress: () => console.log('取消')
			//     },
			//     {
			//         text: '确定',
			//         onPress: () => {
			//             this.setState({
			//                 isSelect: true
			//             }, function () {
			//                 this.checkValue(this.state.inputValue);
			//             });
			//         }
			//     },
			// ]);
		}
	}

	//去充值
	goRecharge() {
		this.props.history.push(`/rechargeAccount`);
	}

	//自定义Number.toField方法
	yhToFixed(tempNum, fractionDigits) {
		// 对fractionDigits做任何处理，假设它是合法输入
		// console.log("yhToFixed", tempNum, fractionDigits);

		if (isNaN(fractionDigits)) {
			throw new Error("The decimal place must be a number");
		}
		//判断小数位数
		let numStr = tempNum.toString().split(".");
		if (numStr.length <= 1) {
			//没有小数，直接添加保留的位数
			let decimalsArr = Array.apply(null, { length: fractionDigits });
			decimalsArr = decimalsArr.map(function () {
				return 0;
			});
			return tempNum.toString() + "." + decimalsArr.join("");
		} else {
			//自定义四舍五入
			let num = parseInt(tempNum * Math.pow(10, fractionDigits + 1)).toString();

			let lastNum = num.slice(-1);
			if (lastNum >= 5) {
				num = Number(num) + 10;
			}
			num = parseInt(num / Math.pow(10, 1)) / Math.pow(10, fractionDigits);

			let decimals = num.toString().split(".");
			if (decimals.length <= 1) {
				return num.toFixed(fractionDigits);
			} else if (decimals.length < fractionDigits) {
				//小数位数不够，添加0
				let decimalsArr = Array.apply(null, {
					length: fractionDigits - decimals.length
				});
				decimalsArr = decimalsArr.map(function () {
					return 0;
				});
				return num + decimalsArr.join("");
			} else {
				return num;
			}
		}
	}

	//输入框校验
	checkValue(value) {
		let inputValue = value;

		let buyBtnClass = "btn buy-btn btn-able";
		let purchaseAbleClass = "purchase-all purchase-able";
		let { isSelect, productBuyInitData } = this.state;
		let tipMessage = productBuyInitData.observeLabel;
		let preValue = this.state.inputValue;

		if (value && !/^(([1-9]\d*)|0)(\.\d{0,2}?)?$/.test(value)) {
			if (value === ".") {
				inputValue = "0.";
			} else {
				inputValue = preValue;
			}
		}
		if (!inputValue) {
			// tipMessage = productBuyInitData.observeLabel;
			buyBtnClass = "btn buy-btn btn-disable";
			if (Number(productBuyInitData.balanceAmt) == 0) {
				purchaseAbleClass = "purchase-all purchase-disable";
			}
		} else if (
			inputValue.toString().substr(inputValue.toString().length - 1, 1) === "."
		) {
			tipMessage = <div style={{ color: "red" }}>请输入正确金额</div>;
			buyBtnClass = "btn buy-btn btn-disable";
		} else {
			if (this.getIncreasedMoneyType()) {
				if (
					Number(productBuyInitData.balanceAmt) != Number(inputValue) &&
					Number(productBuyInitData.balanceAmt) >=
						Number(productBuyInitData.minMoney)
				) {
					purchaseAbleClass = "purchase-all purchase-able";
				} else {
					purchaseAbleClass = "purchase-all purchase-disable";
				}
			} else if (
				parseInt(productBuyInitData.balanceAmt) != parseInt(inputValue) &&
				Number(productBuyInitData.balanceAmt) >=
					Number(productBuyInitData.minMoney)
			) {
				purchaseAbleClass = "purchase-all purchase-able";
			} else {
				purchaseAbleClass = "purchase-all purchase-disable";
			}

			let maxi =
				Number(productBuyInitData.maxTradeAmt).toFixed(2) -
				Number(inputValue).toFixed(2);
			if (maxi.toFixed(2) < 0) {
				tipMessage = <div style={{ color: "red" }}>单笔上限500万</div>;
				buyBtnClass = "btn buy-btn btn-disable";
			}

			let bi =
				Number(productBuyInitData.balanceAmt).toFixed(2) -
				Number(inputValue).toFixed(2);
			if (bi.toFixed(2) < 0) {
				tipMessage = (
					<div style={{ color: "red" }}>电子账户余额不足，请先充值</div>
				);
				purchaseAbleClass = "purchase-all purchase-able";

				inputValue = this.formatMoney(productBuyInitData.balanceAmt);
				if (
					inputValue === productBuyInitData.balanceAmt &&
					productBuyInitData.balanceAmt != 0
				) {
					buyBtnClass = "btn buy-btn btn-able";
				}
			}

			if (Number(inputValue) < Number(productBuyInitData.minMoney)) {
				tipMessage = (
					<div style={{ color: "red" }}>
						转入金额{Number(productBuyInitData.minMoney)}元起
					</div>
				);
				buyBtnClass = "btn buy-btn btn-disable";
			}

			if (
				maxi.toFixed(2) >= 0 &&
				bi.toFixed(2) >= 0 &&
				Number(inputValue) >= Number(productBuyInitData.minMoney)
			) {
				// tipMessage = productBuyInitData.observeLabel;
				if (isSelect || productBuyInitData.contactInfos.length == 0) {
					buyBtnClass = "btn buy-btn btn-able";
				}
			}

			if (!isSelect) {
				buyBtnClass = "btn buy-btn btn-disable";
			}
		}
		if (this.state.productBuyInitData.saleStatus != "1") {
			buyBtnClass = "btn buy-btn btn-disable";
		}
		this.setState({
			tipMessage: tipMessage,
			purchaseAbleClass: purchaseAbleClass,
			buyBtnClass: buyBtnClass,
			inputValue: inputValue
		});
	}

	/**
	 * 递增金额为1元时使用parseInt()
	 * 递增金额为0.01元时使用Number().Fixed(2);
	 */
	formatMoney(m) {
		//步进为0.01
		if (this.getIncreasedMoneyType()) {
			return Number(parseFloat(m)).toFixed(2);
		} else {
			//步进为1元时
			return parseInt(m);
		}
	}
	//查看进步值是不是整数;true 递增是浮点数
	getIncreasedMoneyType() {
		let { productBuyInitData } = this.state;
		let money = productBuyInitData.increasedMoney;
		if (money == "0.01" || parseFloat(money) - parseInt(money) > 0) {
			return true;
		}
		return false;
	}

	render() {
		const _pageParams = {
			header: {
				title: "转入小辉宝",
				goBackPath: "/walletHome"
			},
			history: this.props.history,
			loadStatus: this.state.loadStatus,
			cacheLifecycles: this.props.cacheLifecycles
		};
		let {
			productBuyInitData,
			isSelect,
			inputValue,
			tipMessage,
			buyBtnClass,
			sendSuccessPhone = "",
			showMsgBox
		} = this.state;

		if (!productBuyInitData.contactInfos) {
			productBuyInitData.contactInfos = [];
		}
		return (
			<MainLayout pageParams={_pageParams}>
				<div className="transfer-XHB-into-page">
					<div className="purchase-input">
						<WingBlank>
							<div>
								<div className="purchase-input-area">
									<div className="amount-area">
										<InputItem
											type="money"
											placeholder={productBuyInitData.productLabel}
											onChange={this.checkValue.bind(this)}
											value={inputValue}
											clear
											disabledKeys={this.getIncreasedMoneyType() ? [] : ["."]}
											moneyKeyboardAlign="left"
											extra={
												<div
													onClick={() => this.allBuyAction()}
													className="allChangeInto"
												>
													全部转入
												</div>
											}
										>
											¥
										</InputItem>
									</div>
								</div>
								{tipMessage && (
									<div className="purchase-tip-area">{tipMessage}</div>
								)}
							</div>
						</WingBlank>
					</div>

					<div className="purchase-bank">
						<WingBlank>
							<div>
								<div className="purchase-bank-area">
									<p className="fukuan">付款方式</p>
									<div className="bank-item purchase-bank-item-des">
										<div className="purchase-bank-item-icon"></div>
										<div className="purchase-bank-item-text">
											<div className="purchase-bank-item-name">
												华通银行电子账户({productBuyInitData.electronicCardNo})
											</div>
											<div className="purchase-bank-item-amount">
												可用余额
												<span className="amount-detail">
													{productBuyInitData.balanceAmt}
												</span>
												元
											</div>
										</div>
									</div>
									<div
										className="bank-item purchase-bank-item-recharge"
										onClick={() => this.goRecharge()}
									>
										去充值
									</div>
								</div>
							</div>
						</WingBlank>
					</div>
					<div
						className="purchase-agreement"
						style={
							productBuyInitData.contactInfos.length == 0
								? { display: "none" }
								: { display: "block" }
						}
					>
						<WingBlank>
							<div className="purchase-agreement-area">
								<div
									ref="selectAgree"
									onClick={() => this.selectClick()}
									className={
										isSelect
											? "agreement-item select-icon selected"
											: "agreement-item select-icon noselect"
									}
								></div>
								<div className="agreement-item purchase-agreement-area-text">
									<span className="agreement-des">阅读并同意</span>
									{productBuyInitData.contactInfos.map(value => (
										<span
											key={value.contractDesc}
											className="agreement-content"
											onClick={() => this.proClick(value.contractCode)}
										>
											{"《" + value.contractDesc + "》"}
										</span>
									))}
								</div>
							</div>
						</WingBlank>
					</div>
					<div className="bottom-tips">
						<span>转入说明:</span>
						<p>
							每日23:50至次日0:20（每周日23:00至每周一3:00）因银行及平台系统原因转入、转出均关闭，其他时间正常。
						</p>
					</div>

					<WingBlank>
						<div
							className={buyBtnClass}
							ref="buyProduct"
							onClick={() => this.purchaseClick()}
						>
							{this.getText()}
						</div>
					</WingBlank>
				</div>
				<SendMSGCode
					ref={ref => {
						this.sendCode = ref;
					}}
					getYZMCode={this.sendYzm.bind(this)}
					sendSuccessPhone={sendSuccessPhone}
					submitCode={this.submitCode.bind(this)}
					closeSendModal={this.closeSendModal.bind(this)}
					showMsgBox={showMsgBox}
					seconds={60}
				/>
				<p className="bank-resource">本服务由华通银行提供</p>
			</MainLayout>
		);
	}

	getText() {
		let obj = {
			0: "已停售",
			1: "确认转入",
			2: "已售罄"
		};
		return obj[this.state.productBuyInitData.saleStatus];
	}

	//短信验证码验证接口
	sendYzm() {
		const _this = this;
		let objs = {
			url: "/fm/smsMessage",
			params: {
				channelCode: channelCode
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code == "0") {
				_this.sendCode.countdown();
				_this.setState({
					sendSuccessPhone: res.data.sendSuccessPhone,
					messageSerialNumber: res.data.messageSerialNumber,
					showMsgBox: true //显示验证码
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	//提交回调
	submitCode(code) {
		if (code == "" || code.toString().length < 6) {
			Toast.info("请输入六位验证码", 2);
			return;
		}
		let _that = this;
		let objs = {
			url: "/fm/financeBuy",
			params: {
				channelCode: channelCode,
				productId: _that.state.productId,
				productName: _that.state.productName,
				tradeAmount: _that.state.inputValue,
				activeCode: code,
				messageSerialNumber: this.state.messageSerialNumber //短信流水号
			},
			_alertShow: false
		};
		console.log(JSON.stringify(objs));
		// return;
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				_that.setState({
					showMsgBox: false
				});
				setTimeout(function () {
					_that.props.history.push({
						pathname: `/transferXHBSuccess/into/${JSON.stringify(res.data)}`
					});
				}, 100);
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	//关闭验证码弹框
	closeSendModal() {
		this.setState({
			showMsgBox: false
		});
	}
}

const TransferXHBIntoPage = createForm()(TransferXHBInto);
export default TransferXHBIntoPage;
